package com.parkerchang.encrypt.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.parkerchang.encrypt.properties.EncryptProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * <p>
 * 加解密工具
 * </p>
 *
 * @author Parker
 * @version v1.0
 * @date 2022/5/18 17:26
 */
@Component
@Slf4j
public class EncryptionAndDecryptionUtil {

    @Autowired
    private EncryptProperties encryptProperties;

    /**
     * aes加密对象
     */
    public static SymmetricCrypto AES;
    /**
     * sm4加密对象
     */
    public static SymmetricCrypto SM4;


    /**
     * 组装静态变量
     */
    @PostConstruct
    public void init() {
        byte[] key;
        // 如果没设置就生成默认秘钥
        if (StrUtil.isBlank(encryptProperties.getKey())) {
            key = KeyUtil.generateKey(cn.hutool.crypto.symmetric.SM4.ALGORITHM_NAME).getEncoded();
            log.info("Random key generated by default：{}",HexUtil.encodeHexStr(key));
        }else {
            key = HexUtil.decodeHex(encryptProperties.getKey());
        }
        AES = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        SM4 = SmUtil.sm4(key);
    }
}
